<?php
/**
 * PDF.php
 * Notes:
 * author: chen
 * DateTime: 2022/12/2 13:43
 * @package Xtsb\Cims\File
 */

namespace Xtsb\Cims\File;

use Mpdf\Mpdf;
use setasign\Fpdi\Fpdi;
use setasign\Fpdi\PdfParser\StreamReader;
use think\Exception;
use setasign\Fpdi\PdfParser\CrossReference\CrossReferenceException;

class PDF
{
  public static function pdf($filepath, $stamps = [])
  {
    $mpdf = new Mpdf([
      'mode' => 'zh-cn',//显示中文
//      'format' => [210, 297], //纸张大小
      'format' => 'A4', //纸张大小
      'margin_left' => 0, //设置左边距
      'margin_right' => 0, //设置右边距
      'margin_top' => 0, //设置上边距
      'margin_bottom' => 0,//设置下边距
      'margin_header' => 0,//设置头边距
      'margin_footer' => 0,//设置脚边距
//      'orientation' => 'L', //设置为横屏
      'default_font_size' => 8,//字号
    ]);

    //开启字段文字和样式
//    $mpdf->autoScriptToLang = true;
//    $mpdf->autoLangToFont = true;
//    $mpdf->use_kwt = false;

// set the sourcefile
    $mpdf->setSourceFile($filepath); // absolute path to pdf file

    if (empty($stamps)) {
      return false;
    }
//    $pages=[];
//    foreach ($stamps as $stamp) {
//      $pages[$stamp['']]
//    }
    $pages = array_column($stamps, 'width,height,x,y,page', 'page');
dd($pages);
//    dd($mpdf->nb);
    $tplIdx = $mpdf->importPage(1);
    $mpdf->useTemplate($tplIdx, 0, 0, 210);

//    $mpdf->SetXY(0, 215 * 0.42);
    $mpdf->SetXY(0, 0.1);
    $left = 229;
    $top = 206;
    $mpdf->WriteHTML('<div style="color: red;font-weight: bold;margin-left: ' . $left . 'px;margin-top: ' . $top . 'px;">蔺相如</div>');

    $mpdf->SetXY(0, 0.1);
    $left = 185;
    $top = 230;
    $mpdf->WriteHTML('<div style="color: red;font-weight: bold;margin-left: ' . $left . 'px;margin-top: ' . $top . 'px;">公孙无敌</div>');

    $mpdf->AddPage();

    $tplIdx = $mpdf->importPage(2);
    $mpdf->useTemplate($tplIdx, 0, 0, 210);
    $mpdf->AddPage();


// import page 1
    $tplIdx = $mpdf->importPage(3);
// use the imported page and place it at point 10,10 with a width of 200 mm   (This is the image of the included pdf)
    $mpdf->useTemplate($tplIdx, 0, 0, 210);

// now write some text above the imported page
    $mpdf->SetTextColor(0, 0, 255);
    $mpdf->SetFont('宋体', 'B', 10);
//    $mpdf->SetXY(-10, 10);
//    $mpdf->SetXY(0, 460 * 0.42);
    $mpdf->SetXY(0, 0.1);
    $left = 153;
    $top = 775;
    $mpdf->WriteHTML('<div style="color: red;font-weight: bold;margin-left: ' . $left . 'px;margin-top: ' . $top . 'px;">乙方签章</div>');

//    $mpdf->SetXY(0, 381 * 0.42);//44.64
    $mpdf->SetXY(0, 0.1);
    $left = 153;
//    $top = 460 * 1.34;
    $top = 819;
    $mpdf->WriteHTML('<div style="color: red;font-weight: bold;margin-left: ' . $left . 'px;margin-top: ' . $top . 'px;">甲方印章</div>');

    //设置水印文字
//    $mpdf->SetWatermarkText('信钛速保');
//    $mpdf->showWatermarkText = true;

    //设置水印图片
//    $mpdf->SetWatermarkImage('test.jpg');
//    $mpdf->showWatermarkImage = true;

    //分页
//    $mpdf->setFooter("Page {PAGENO} of {nb}");

    $mpdf->Output('testnew' . date('YmdHis') . '.pdf');

    return true;
  }

  /**
   * 复制pdf
   * @param $filepath
   * @param $newFile
   * @param array $pageList
   *                 page 页数
   *                 x   坐标x
   *                 y  坐标y
   *                 content 内容
   */
  public static function copyPdf($filePath, $newFile = null, $pageList = [])
  {

    $mpdf = new Mpdf(['mode' => 'zh-cn']);
    $pageCount = $mpdf->setSourceFile($filePath);

    $pageList = !empty($pageList) ? $pageList : [];
    for ($i = 1; $i <= $pageCount; $i++) {
      $importPage = $mpdf->importPage($i);
      $mpdf->UseTemplate($importPage);

      foreach ($pageList as $pageInfo) {
        if ($pageInfo['page'] == $i) {
          $color = '';
          $weight = '100';
          $fontSize = '14';
          if (!empty($pageInfo['font_weight'])) {
            $weight = $pageInfo['font_weight'];
          }
          if (!empty($pageInfo['color'])) {
            $color = $pageInfo['color'];
          }
          if (!empty($pageInfo['font_size'])) {
            $fontSize = $pageInfo['font_size'];
          }

          // 控制超出页数 开始
          $maxX = 700;
          $maxY = 1040;
          if ($pageInfo['x'] >= $maxX) {
            $pageInfo['x'] = $maxX;
          }
          if ($pageInfo['y'] >= $maxY) {
            $pageInfo['y'] = $maxY;
          }
          $length = mb_strlen($pageInfo['content']);
          $xx = $length * 4.5 - ($maxX - $pageInfo['x']);
          $yy = $length * 4.5 - ($maxY - $pageInfo['y']);
          if ($xx > 0) {
            $pageInfo['x'] -= $xx * 0.8;
          }
          if ($yy > 0) {
            $pageInfo['y'] -= $yy * 0.2;
          }
          // 控制超出页数 结束


          $mpdf->SetXY(0, 0.1);
          $rateX = 0.9567;
          $rateY = 0.9613;
          $diffX = -48;
          $diffY = 34.5;
          $y = intval($pageInfo['y'] * $rateY + $diffY);
          $x = intval($pageInfo['x'] * $rateX + $diffX);
          $format = '<div style="color: %s;font-weight:%s;font-size: %s;margin-top: %spx;margin-left:%spx;">%s</div>';
          $mpdf->WriteHTML(sprintf($format, $color, $weight, $fontSize, $y, $x, strval($pageInfo['content'])));
        }
      }
      if ($i < $pageCount) {
        $mpdf->AddPage();
      }
    }
    if ($newFile) {
      $mpdf->OutputFile($newFile);
    } else {
      return $mpdf->Output();
    }
  }

  //pdf多页文件拆分为多个单页文件
  static function split($inputPdfFile){
    try {
      $fixedUrl = str_replace(' ', '%20', $inputPdfFile);
      $fileContent = file_get_contents($fixedUrl);
      $totalPages = (new \Mpdf\Mpdf())->setSourceFile(StreamReader::createByString($fileContent));
      if($totalPages == 1){
        return [];
      }
      $inputFileInfo = pathinfo($inputPdfFile);
      $file_list = [];
      for ($pageNumber = 1; $pageNumber <= $totalPages; $pageNumber++) {
        $mpdf =  new \Mpdf\Mpdf();
        $mpdf->setSourceFile(StreamReader::createByString($fileContent));
        $mpdf->AddPage();
        $id = $mpdf->importPage($pageNumber);
        $mpdf->useTemplate($id);
        $outputPdfFile =  "./storage/temp/{$inputFileInfo['filename']}_{$pageNumber}.pdf";
        $mpdf->Output($outputPdfFile, 'F');
        array_push($file_list,$outputPdfFile);
      }
      return $file_list;
    }catch (CrossReferenceException $e) {
      // 处理 CrossReferenceException 异常
      return [];
    }catch (Exception $e){
      return [];
    }
  }


}
